package reduce.fz.com.reduce.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.TypeReference;
import com.ta.utdid2.android.utils.StringUtils;
import com.umeng.message.ALIAS_TYPE;
import com.umeng.message.PushAgent;
import com.umeng.message.UmengRegistrar;
import com.umeng.update.UmengUpdateAgent;

import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import reduce.fz.com.reduce.R;
import reduce.fz.com.reduce.abstracts.AbResponseListener;
import reduce.fz.com.reduce.bean.ServiceException;
import reduce.fz.com.reduce.bean.User;
import reduce.fz.com.reduce.bean.result.Result;
import reduce.fz.com.reduce.custom.LoadingDialog;
import reduce.fz.com.reduce.service.UserService;
import reduce.fz.com.reduce.service.preference.UserPreference;
import reduce.fz.com.reduce.util.ServiceBuilder;
import reduce.fz.com.reduce.util.ToastUtil;

public class FirstActivity extends BaseActivity implements View.OnClickListener, PlatformActionListener {
    //注册
    private TextView mTvRegister;
    //登录
    private TextView mTvLogin;
    //qq登录
    private LinearLayout mLlqqBtn;
    //微信登录
    private LinearLayout mLlwebchatBtn;
    //微博登录
    private LinearLayout mLlWeiboBtn;
    //平台
    private String platform;
    public LoadingDialog dialog = null;
    //访问token
    private String access_token;

    private static final int SHOW_DIALOG = 1;
    private static final int DIS_DIALOG = 2;

    private UserService userService = ServiceBuilder.builderUserService(null);


    Handler hmessage = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            if (msg.what == SHOW_DIALOG) {
                dialog = new LoadingDialog(FirstActivity.this);
                dialog.setMsg("请稍候");
                dialog.show();
            } else if (msg.what == DIS_DIALOG) {
                if (dialog != null && dialog.isShowing())
                    dialog.dismiss();
            }
            super.handleMessage(msg);
        }
    };


    public void enableYMMessage() {
        PushAgent mPushAgent = PushAgent.getInstance(getBaseContext());
        mPushAgent.enable();
        String device_token = UmengRegistrar.getRegistrationId(getBaseContext());
        //Alb2vxJR6k75lkPv4o_QMTzNFKES9WHaqi79ON4oAXg1
        String a = device_token;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        forwardGuide();
        enableYMMessage();
        UmengUpdateAgent.setUpdateOnlyWifi(false);
        UmengUpdateAgent.update(this);
        initWidget();
        initListener();
    }

    public void forwardGuide() {
        Intent intent = new Intent(this, GuideActivity.class);
        startActivity(intent);
    }


    @Override
    public int getContentRid() {
        return R.layout.activity_first;
    }


    public void initWidget() {
        mTvRegister = (TextView) this.findViewById(R.id.tv_register);
        mTvLogin = (TextView) this.findViewById(R.id.tv_login);
        mLlqqBtn = (LinearLayout) findViewById(R.id.ll_qq_login_btn);
        mLlwebchatBtn = (LinearLayout) findViewById(R.id.ll_webchat_login_btn);
        mLlWeiboBtn = (LinearLayout) findViewById(R.id.ll_weibo_login_btn);
        mLlqqBtn.setOnClickListener(this);
        mLlwebchatBtn.setOnClickListener(this);
        mLlWeiboBtn.setOnClickListener(this);

    }

    public void initListener() {
        /*登录监听登录*/
        mTvLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(FirstActivity.this, LoginActivity.class);
                startActivity(intent);
            }
        });
        /*注册监听注册*/
        mTvRegister.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(FirstActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }


    /**
     * qq登陆
     */
    public void qqLogin() {
        hmessage.sendEmptyMessage(SHOW_DIALOG);
        ShareSDK.closeDebug();
        ShareSDK.initSDK(FirstActivity.this);
        Platform qq = ShareSDK.getPlatform(QQ.NAME);
        qq.SSOSetting(false);  //设置false表示使用SSO授权方式
        qq.setPlatformActionListener(FirstActivity.this); // 设置分享事件回调
        qq.authorize();
        hmessage.sendEmptyMessage(DIS_DIALOG);
    }

    /**
     * 微博登陆
     */
    public void weiboLogin() {
        ShareSDK.closeDebug();
        ShareSDK.initSDK(FirstActivity.this);
        Platform weibo = ShareSDK.getPlatform(SinaWeibo.NAME);
        if (weibo == null) {
            ToastUtil.showMessage("微博登录异常");
            return;
        }
        weibo.SSOSetting(false);  //设置false表示使用SSO授权方式
        weibo.setPlatformActionListener(FirstActivity.this); // 设置分享事件回调
        weibo.authorize();
    }

    /**
     * webcht登陆
     */
    public void webchatLogin() {
        ShareSDK.closeDebug();
        ShareSDK.initSDK(FirstActivity.this);
        Platform wechat = ShareSDK.getPlatform(Wechat.NAME);
        wechat.SSOSetting(false);  //设置false表示使用SSO授权方式
        wechat.setPlatformActionListener(FirstActivity.this); // 设置分享事件回调
        wechat.authorize();
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_qq_login_btn:
                qqLogin();
                //  ToastUtil.showMessage("暂不可用!");
                break;
            case R.id.ll_webchat_login_btn:
                webchatLogin();
                //ToastUtil.showMessage("微信审核尚未通过,请先使用QQ登录");
                break;
            case R.id.ll_weibo_login_btn:
                weiboLogin();
                // ToastUtil.showMessage("暂不可用!");
                break;
            default:
                break;

        }

    }

    @Override
    public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
        PlatformDb db = platform.getDb();
        int pid = platform.getId();
        if (pid == 4) {
            this.platform = "wechat";
        } else if (pid == 1) {
            this.platform = "weibo";
        } else if (pid == 7) {
            this.platform = "qq2";
        }
        User user = new User();
        user.platform = this.platform;
        user.openid = db.getUserId();
        user.token = db.getToken();
        user.nickname = db.getUserName();
        String gender = db.getUserGender();
        if (!StringUtils.isEmpty(gender)) {
            user.sex = gender.toUpperCase();
        }
        user.refresh_token = db.get("refresh_token");
        user.expires_in = db.getExpiresIn();
        user.intr = db.get("resume");
        user.avatar = db.getUserIcon();
        hmessage.sendEmptyMessage(SHOW_DIALOG);
        userService.socialBind(user, new AbResponseListener<User>(new TypeReference<Result<User>>() {
        }) {
            @Override
            public void error(ServiceException e) {
                hmessage.sendEmptyMessage(DIS_DIALOG);

            }

            @Override
            public void responseInfo(final Result<User> data) {
                hmessage.sendEmptyMessage(DIS_DIALOG);
                final PushAgent mPushAgent = PushAgent.getInstance(getBaseContext());
                mPushAgent.enable();
                try {
                   // mPushAgent.addAlias(data.getData().uid + "", ALIAS_TYPE.SINA_WEIBO);
                    String device_token = UmengRegistrar.getRegistrationId(getBaseContext());
                    new Thread(){
                        @Override
                        public void run() {
                            try {
                                Boolean isadd=mPushAgent.addExclusiveAlias(data.getData().uid + "", "yixiu");
                                int a=1;
                                System.out.print("111");
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }.start();

                    System.out.print("111");
                } catch (Exception e) {
                    e.printStackTrace();
                }



                UserPreference.saveUser(data.getData());
                forwardMainContent();

            }
        });
    }




    /**
     * 进入首页
     */
    public void forwardMainContent() {
        Intent intent = new Intent(this, DoorActivity.class);
        startActivity(intent);
    }


    @Override
    public void onError(Platform platform, int i, Throwable throwable) {

    }

    @Override
    public void onCancel(Platform platform, int i) {

    }
}
